package com.ajieee.merge.runner.finance.proxy;

import com.ajieee.merge.entity.finance.po.EtfInfoPO;
import com.ajieee.merge.entity.finance.po.EtfQuotePO;
import com.ajieee.merge.enums.finance.Exchange;
import com.ajieee.merge.util.DateUtils;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ajieee
 * @date 2025-10-02
 */
@Component
@RequiredArgsConstructor
public class SseProxy {

	private final RestClient restClient;

	/**
	 * 获取上交所ETF基本信息
	 */
	public List<EtfInfoPO> getSseEtfInfo() {
		String uri = UriComponentsBuilder.fromUriString("https://query.sse.com.cn/commonSoaQuery.do")
				.queryParam("isPagination", false)
				.queryParam("sqlId", "FUND_LIST")
				.queryParam("fundType", "00")
				.build().encode().toUriString();
		JsonNode respNode = restClient.get()
				.uri(uri)
				.header("Referer", "https://www.sse.com.cn/")
				.retrieve()
				.body(JsonNode.class);
		if (respNode == null) {
			throw new RuntimeException("没有数据");
		}
		JsonNode data = respNode.get("pageHelp").get("data");
		List<EtfInfoPO> pos = new ArrayList<>(data.size());
		data.forEach(node -> {
			EtfInfoPO po = new EtfInfoPO();
			po.setFundCode(node.get("fundCode").asText());
			po.setFundName(node.get("secNameFull").asText());
			po.setExchange(Exchange.SSE);
			po.setListDate(DateUtils.parseDate(node.get("listingDate").asText(), "yyyyMMdd"));
			pos.add(po);
		});

		return pos;
	}

	public List<EtfQuotePO> getEtfHistoryQuote(String fundCode) {
		String uriString = UriComponentsBuilder.fromUriString("https://yunhq.sse.com.cn:32042/v1/sh1/dayk/" + fundCode)
				.queryParam("begin", 0)
				.queryParam("end", -1)
				.queryParam("period", "day")
				.queryParam("select", "date,open,high,low,close,change,chg_rate,volume,amount")
				.build().encode().toUriString();
		JsonNode root = restClient.get()
				.uri(uriString)
				.header("Referer", "https://www.szse.cn/market/trend/index.html")
				.retrieve()
				.body(JsonNode.class);
		Assert.notNull(root, "没有数据");

		List<EtfQuotePO> pos = new ArrayList<>(root.get("total").asInt());
		JsonNode data = root.get("kline");
		for (JsonNode node : data) {
			EtfQuotePO po = new EtfQuotePO();
			LocalDate dataDate = DateUtils.parseDate(node.get(0).asText(), "yyyyMMdd");
			po.setDataDate(dataDate);
			po.setFundCode(fundCode);
			po.setOpen(node.get(1).asDouble());
			po.setHigh(node.get(2).asDouble());
			po.setLow(node.get(3).asDouble());
			po.setClose(node.get(4).asDouble());
			po.setChange(node.get(5).asDouble());
			po.setChangeRatio(node.get(6).asDouble());
			po.setVolume(node.get(7).asDouble());
			po.setAmount(node.get(8).asDouble());
			pos.add(po);
		}
		return pos;
	}
}
